<template>
  <div class="publish">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文章管理</el-breadcrumb-item>
      <el-breadcrumb-item>文章发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card" style="margin-top: 20px">
      <el-form ref="form" :model="post" label-width="80px" :rules="rules">
        <!-- 标题 -->
        <el-form-item label="标题:" prop="title">
          <el-input v-model="post.title"></el-input>
        </el-form-item>
        <el-form-item label="类型:">
          <el-radio-group v-model="post.type">
            <el-radio :label="1">文章</el-radio>
            <el-radio :label="2">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容:" prop="content">
          <!-- 富文本框 -->
          <!-- vue中直接操作DOM元素,就必须用ref属性进行注册 -->
          <VueEditor :config="config" v-if="post.type == 1" ref="vueEditor" />
          <!-- 视频文件上传 -->
          <el-upload
            v-if="post.type == 2"
            class="upload-demo"
            action="http://127.0.0.1:3000/upload"
            :headers="getToken()"
            :on-success="onSuccess"
            multiple
            :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
          </el-upload>
        </el-form-item>

        <!-- 栏目 -->
        <el-form-item label="栏目:">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="cates"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="item in cateList"
              :label="item.id"
              :key="item.id"
              >{{ item.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <!-- 封面 -->
        <el-form-item label="封面:">
          <el-upload
            action="http://127.0.0.1:3000/upload"
            :headers="getToken()"
            list-type="picture-card"
            :on-success="CoverSuccess"
            :on-remove="CoverRemove"
            ><i class="el-icon-plus"></i></el-upload
          ><el-dialog>
            <img width="100%" alt="" />
          </el-dialog>
        </el-form-item>

        <el-button type="primary" style="margin-left: 75px" @click="publish"
          >发布文章</el-button
        >
      </el-form>
    </el-card>
  </div>
</template>

<script>
import VueEditor from "vue-word-editor";
import "quill/dist/quill.snow.css";
import { publishPost } from "@/apis/post.js";
import { getCateList } from "@/apis/category.js";
export default {
  data() {
    return {
      isIndeterminate: false,
      checkAll: false,
      cates: [],
      cateList: [],
      fileList: [],
      post: { title: "", content: "", type: 1, cover: [], categories: [] },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
      },
      // 请配置上传回调函数
      config: {
        //上传图片的配置
        uploadImage: {
          url: "http://127.0.0.1:3000/upload",
          name: "file",
          // 添加token的传递
          headers: {
            Authorization: localStorage.getItem("heima_back_token_59"),
          },
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            console.log(res);
            insert("http://localhost:3000" + res.data.data.url);
          },
        },

        //上传视频的配置
        uploadVideo: {
          url: "http://localhost:3000/upload",
          name: "file",
          // 添加token的传递
          headers: this.getToken(),
          // res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
          uploadSuccess(res, insert) {
            console.log(res);
            insert("http://localhost:3000" + res.data.data.url);
          },
        },
      },
    };
  },
  async mounted() {
    let res = await getCateList();
    // 关注 和 头条 不参与用户交互
    this.cateList = res.data.data.slice(2);
    console.log(this.cateList);
  },
  methods: {
    handleCheckAllChange(val) {
      // cates数组中的值决定了那些复选框被选中，它是的id数组(里面的每个值都是id)
      // 所以，所谓全选功能的实现就是给它一个数组包含所有栏目数据的id,全不选就给它一个空值数组
      this.cates = val
        ? this.cateList.map((v) => {
            return v.id;
          })
        : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      console.log(value);
      let checkedCount = value.length; // 获取选中的复选框的数量
      // 设置全选状态
      this.checkAll = checkedCount === this.cateList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cateList.length;
    },

    async publish() {
      // console.log(this.post);
      // 如果是文章，就获取富文本框的数据
      if (this.post.type == 1) {
        this.post.content = this.$refs.vueEditor.editor.root.innerHTML;
      }

      // 改造categories
      this.post.categories = this.cates.map((v) => {
        return { id: v };
      });
      console.log(this.post);

      let res = await publishPost(this.post);
      console.log(res);
      if (res.data.message == "文章发布成功") {
        this.$message({
          type: "success",
          message: "文章发布成功",
        });
        this.$router.push({ path: "postlist" });
      }
    },
    getToken() {
      return { Authorization: localStorage.getItem("heima_back_token_59") };
    },
    // 内容块视频文件上传成功之后的触发函数
    onSuccess(response) {
      if (response.message == "文件上传成功") {
        this.post.content = response.data.url;
        // console.log(response);
      }
    },
    //file:当前被移除的文件
    //filesList:当前被保留的文件
    CoverRemove(file, filesList) {
      console.log(file, "---", filesList);
      let id = file.response.data.id;
      // 将这个id所对应的数据从cover数组中删除
      console.log("1", this.post.cover);

      for (let i = 0; i < this.post.cover.length; i++) {
        if (this.post.cover[i].id == id) {
          // 找到了
          this.post.cover.splice(i, 1);
          break;
        }
      }
      // console.log("2", this.post.cover);
    },
    CoverSuccess(response, file, filesList) {
      console.log(response, file, filesList);
      if (response.message == "文件上传成功") {
        this.post.cover.push({ id: response.data.id });
      }
    },
  },
  components: {
    VueEditor,
  },
};
</script>

<style>
</style>